package com.zhugang.week08;

import java.util.*;

/**
 * @program algorithms
 * @description: permuteUnique
 * @author: chanzhugang
 * @create: 2022/08/05 15:38
 */
public class PermuteUnique {

    /**
     * 47 全排列 II
     *
     * @param nums
     * @return
     */
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        // nums中包含重复数字， 全排列
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int count = 1;
            if (map.containsKey(nums[i])) {
                count += map.get(nums[i]);
            }
            map.put(nums[i], count);
        }

        int n = map.size();
        int[] uniqueNums = new int[n];
        int[] counts = new int[n];
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                uniqueNums[k] = nums[i];
                counts[k] = map.get(nums[i]);
                k++;
                map.remove(nums[i]);
            }
        }
        // 回溯
        backtrack(uniqueNums, counts, 0, new ArrayList<Integer>(), nums.length);
        return result;
    }

    private void backtrack(int[] uniqueNums, int[] counts, int k, ArrayList<Integer> path, int n) {
        if (k == n) {
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < uniqueNums.length; i++) {
            if (counts[i] == 0) {
                continue;
            }
            // 添加选择
            path.add(uniqueNums[i]);
            counts[i]--;
            backtrack(uniqueNums, counts, k + 1, path, n);
            // 撤销选择
            path.remove(path.size() - 1);
            counts[i]++;
        }
    }

}